<!---->
<template>
  <div class="manage">
    <h3>新增数据</h3>
      <h4>数据操作</h4>
    <div class="nav">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="添加博客" name="first">
            <div class="wrap">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item prop="title">
          <el-input
            v-model="ruleForm.title"
            placeholder="请输入文章标题（5-50个字）"
            maxlength="50"
            minlength="5"
            show-word-limit
            clearable
          ></el-input>
        </el-form-item>
        <div id="vditor" style="text-align:left"></div>
        <div class="sel">
          <el-select v-model="ruleForm.category" placeholder="请选择文章分类">
            <el-option
              v-for="item in category"
              :key="item.categoryname"
              :label="item.categoryname"
              :value="item.categoryname"
            >
            </el-option>
          </el-select>
        </div>
        <div style="margin:20px 0;width:500px">
          <el-form-item label="文章封面">
            <el-upload
              class="avatar-uploader"
              action="api/UploadImg"
              :multiple="false"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </div>
        <div class="btn">
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >提交</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
      <!-- <span class="titlenum">{{ titlenum }}</span> -->
    </div>
        </el-tab-pane>
        <el-tab-pane label="添加用户" name="second">
            <addUser></addUser>
        </el-tab-pane>
        <el-tab-pane label="添加分类" name="third">
            <addCategroy></addCategroy>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import<组件名字> from '<组件路径>';
import commTab from "@/components/tab";
import commPage from '@/components/page.vue';
import addUser from '@/components/adduser.vue'
import addCategroy from '@/components/categroy.vue'
import Vditor from "vditor";
import "vditor/dist/index.css";
export default {
  //import引入的组件需要注入对象中才能用
  components: {
    commTab: commTab,
    commPage:commPage,
    addUser:addUser,
    addCategroy:addCategroy
  },
  data() {
    return {
      imageUrl: '',
      fileList: [],
      value1: "",
      activeName: "first",
      category: [],
      titlenum: "0",
      contentEditor: "",
      input: "",
      ruleForm: {
        title: "", //标题
        category: "", //类别
        content: "", //内容
      },
      rules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          {
            min: 5,
            max: 50,
            message: "长度在 5 - 50 个字符",
            trigger: "blur",
          },
        ],
        category: [
          { required: true, message: "请选择文章分类", trigger: "change" },
        ],
      },
      postData: {
        pageNo: "1",
        pageSize: "5",
        categroy: "allin",
      },
      pageData: {},
    };
  },
  //监听属性 类似于data概念
  computed: {
    user(){
      if(sessionStorage.getItem("user")){
        this.$store.commit("setUserObj",JSON.parse(sessionStorage.getItem("user")))
      }else{
        this.$store.commit("setUserObj",null)
      }
      return this.$store.state.userObj
    }
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
      handleClick(tab, event) {
      console.log(tab, event);
    },
    //添加文章
    submitForm(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          if (
            this.contentEditor.getValue().length == 1 ||
            this.contentEditor.getValue() == null ||
            this.contentEditor.getValue() == ""
          ) {
            alert("文章内容不可为空");
            return false;
          }
          this.ruleForm.content = this.contentEditor.getValue();
          this.ruleForm.author = this.user.nickname
          this.ruleForm.userid = this.user.id
          this.API.addBlog(this.ruleForm).then(res=>{
            if(res.message.code == 200){
              this.contentEditor.setValue("")
              this.ruleForm.title = ""
              this.ruleForm.category = ""
              this.imageUrl = ''
              this.$message({
                message:res.message.msg,
                type:'success'
              })
              
            }else{
              this.$message({
                message:res.message.msg,
                type:'error'
              })
            }
          })
          console.log("数据", this.ruleForm);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(ruleForm) {
      this.$refs[ruleForm].resetFields();
    },
    //获取列表
    getList(){
        this.API.getCategoryList(this.postData).then((res) => {
      if (res.message.code == 200) {
        this.category = res.data.pageData || [];
        const { currenPage, hasNext, hasPre, pageCount, pageSize } = res.data;
        this.pageData.currenPage = currenPage;
        this.pageData.hasNext = hasNext;
        this.pageData.hasPre = hasPre;
        this.pageData.pageCount = pageCount;
        this.pageData.pageSize = pageSize;
        console.log("获取列表成功");
      } else {
        console.log("获取列表失败");
      }
    });
    },
    handlePictureCardPreview(file) {
      console.log("file", file);
      this.dialogImageUrl = file.response.data; //拿到路径放大图片
      this.dialogVisible = true;
    },
    //获取图片路径
    handleAvatarSuccess(res, file) {
      console.log("shishen",file)
        this.ruleForm.imgPath = file.response.data;
        this.imageUrl = file.response.data
        console.log("dd",this.ruleForm.imgPath)
      },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期-挂载完成（可以访问DOM元素）
  mounted() {
      this.contentEditor = new Vditor("vditor", {
      height: 400,
      minHeight: 300,
      placeholder: "请输入文章内容",
      toolbarConfig: {
        pin: true,
      },
      counter: {
        enable: true,
      },
      cache: {
        enable: false,
      },
      after: () => {
        this.contentEditor.setValue(""); //数据回显
      },
    });
    this.getList()
  },
  beforeCreate() {}, //生命周期-创建之前
  beforeMount() {}, //生命周期-挂载之前
  beforeUpdate() {}, //生命周期-更新之前
  updated() {}, //生命周期-更新之后
  beforeDestroy() {}, //生命周期-销毁之前
  destroyed() {}, //生命周期-销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个会输会触发
};
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<style lang='less' scoped>
//@import url(); 引入公共css类
.manage {
  overflow:auto;
  margin: 20px;
  padding: 0 20px;
  border-radius: 10px;
  background: #fff;
  // height:800px;
  height: 100%;
  h3,
  h4 {
    text-align: left;
  }
  h4 {
    color: rgb(64, 158, 255);
  }
}
.wrap {
    position: relative;
    // margin: 20px 0;
    .btn {
    //   position: fixed;
    //   bottom: 0;
    //   background-color: #fff;
    //   left: 0;
    //   right: 0;
    //   border-top: 1px solid #e8e8e8;
    //   z-index: 8;
    //   height: 70px;
    //   text-align: center;
    //   line-height: 70px;
    padding:60px 0;
      .el-form-item{
          margin: 0 !important;
          height:100%;
          line-height: 70px;
          
      }
      .el-form-item__content{
              line-height: 70px !important;
          }
    }
  }
.el-button {
  width: 115px;
}
.el-select {
  width: 100%;
}
</style>